import { Module } from 'vuex'
import { ILoginState, IRootState } from '../types'
import { mapMenuToRoutes, mapMenusToPermissions } from '@/utils/map-menus'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenuByRoleId
} from '../../service/login/login'
import { IAccount } from '../../service/login/type'
import localCache from '@/utils/caches'
import router from '@/router'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeMenus(state, userMenus: any) {
      //注册动态路由
      state.userMenus = userMenus
      const routes = mapMenuToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      //获取用户权限
      const permission = mapMenusToPermissions(userMenus)
      state.permissions = permission
    }
  },
  getters: {},
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      //请求TOKEN
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult?.data
      commit('changeToken', token)
      localCache.setCache('token', token)
      //拿到部门信息
      dispatch('getInitialDataAction', null, { root: true })
      //请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult?.data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)
      //请求用户菜单
      const userMenuResult = await requestUserMenuByRoleId(userInfo.role.id)
      const userMenus = userMenuResult.data
      commit('changeMenus', userMenus)
      localCache.setCache('userMenus', userMenus)
      //跳转到首页
      router.push('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getcache('token')
      if (token) {
        commit('changeToken', token)
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getcache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getcache('userMenus')
      if (userMenus) {
        commit('changeMenus', userMenus)
      }
    }
  }
}
export default loginModule
